package io.xxx.mario.task.convert;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import io.xxx.mario.task.*;
import io.xxx.mario.task.api.MessageRequest;
import io.xxx.mario.task.api.UpdateTaskRequest;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.core.convert.converter.Converter;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class UpdateTaskRequestConverter implements Converter<UpdateTaskRequest, Task> {

    @Resource
    private TaskMapper taskMapper;

    @Override
    public Task convert(@NonNull UpdateTaskRequest source) {
        Task oldTask = taskMapper.selectById(source.getId());

        List<MessageRequest> messages = source.getMessages();
        List<Long> roomIds = source.getRoomIds();

        Task task = new Task();
        BeanUtils.copyProperties(source, task);

        LocalDateTime now = LocalDateTime.now();
        task.setId(IdWorker.getId());
        task.setStatus(TaskStatus.NEW);
        task.setProcess(0.0);
        task.setCreatedTime(now);
        task.setUpdatedTime(now);
        task.setUpdatedId(task.getCreatedId());
        task.setUpdatedName(task.getCreatedName());

        AtomicInteger serialNo = new AtomicInteger();
        List<TaskMessage> taskMessages = messages.stream()
                .map(message -> {
                    TaskMessage tm = new TaskMessage();
                    tm.setId(IdWorker.getId());
                    tm.setSerialNo(serialNo.incrementAndGet());
                    tm.setTaskId(task.getId());
                    BeanUtils.copyProperties(message, tm);
                    tm.setCreatedTime(now);
                    return tm;
                })
                .toList();
        task.setMessages(taskMessages);

        List<TaskRoom> taskRooms = roomIds.stream()
                .map(roomId -> {
                    TaskRoom tr = new TaskRoom();
                    tr.setId(IdWorker.getId());
                    tr.setTaskId(task.getId());
                    tr.setRoomId(roomId);
                    tr.setCreatedTime(now);
                    return tr;
                })
                .toList();
        task.setRooms(taskRooms);
        return task;
    }
}
